#!/usr/bin/env python3
"""
性能测试脚本

测试优化后的配置管理和Git操作性能。
"""

import sys
import time
from pathlib import Path

# 添加src目录到Python路径
sys.path.insert(0, str(Path(__file__).parent / "src"))

from src.config.config_manager import ConfigManager
from src.git_ops.git_handler import GitHandler
from src.auto_committer import AutoCommitter


def test_config_performance():
    """测试配置管理性能"""
    print("🔧 测试配置管理性能...")
    
    config_manager = ConfigManager("config")
    
    # 测试缓存机制
    print("📊 测试配置缓存机制:")
    
    # 第一次加载（从文件）
    start_time = time.time()
    config1 = config_manager.load_config(force_reload=True)
    first_load_time = time.time() - start_time
    print(f"   首次加载时间: {first_load_time:.4f}秒")
    
    # 第二次加载（从缓存）
    start_time = time.time()
    config2 = config_manager.load_config(force_reload=False)
    cached_load_time = time.time() - start_time
    print(f"   缓存加载时间: {cached_load_time:.4f}秒")
    
    # 计算性能提升
    if first_load_time > 0:
        improvement = ((first_load_time - cached_load_time) / first_load_time) * 100
        print(f"   性能提升: {improvement:.1f}%")
    
    # 多次连续加载测试
    print("\n📈 连续加载测试 (10次):")
    start_time = time.time()
    for i in range(10):
        config_manager.load_config(force_reload=False)
    total_time = time.time() - start_time
    print(f"   总时间: {total_time:.4f}秒")
    print(f"   平均时间: {total_time/10:.4f}秒/次")
    
    return config1 == config2


def test_git_performance():
    """测试Git操作性能"""
    print("\n🔧 测试Git操作性能...")
    
    git_handler = GitHandler(".")
    
    if not git_handler.is_valid_repo():
        print("   ❌ 当前目录不是有效的Git仓库")
        return False
    
    print("📊 测试Git状态缓存机制:")
    
    # 第一次检查（实际操作）
    start_time = time.time()
    status1 = git_handler.check_status(use_cache=False)
    first_check_time = time.time() - start_time
    print(f"   首次检查时间: {first_check_time:.4f}秒")
    
    # 第二次检查（使用缓存）
    start_time = time.time()
    status2 = git_handler.check_status(use_cache=True)
    cached_check_time = time.time() - start_time
    print(f"   缓存检查时间: {cached_check_time:.4f}秒")
    
    # 计算性能提升
    if first_check_time > 0:
        improvement = ((first_check_time - cached_check_time) / first_check_time) * 100
        print(f"   性能提升: {improvement:.1f}%")
    
    # 多次连续检查测试
    print("\n📈 连续状态检查测试 (5次):")
    start_time = time.time()
    for i in range(5):
        git_handler.check_status(use_cache=True)
    total_time = time.time() - start_time
    print(f"   总时间: {total_time:.4f}秒")
    print(f"   平均时间: {total_time/5:.4f}秒/次")
    
    return True


def test_auto_committer_performance():
    """测试自动提交器性能"""
    print("\n🔧 测试自动提交器性能...")
    
    auto_committer = AutoCommitter("config")
    
    print("📊 测试仓库状态获取:")
    
    # 测试获取所有仓库状态
    start_time = time.time()
    status_list = auto_committer.get_all_repo_status()
    status_time = time.time() - start_time
    print(f"   获取状态时间: {status_time:.4f}秒")
    print(f"   仓库数量: {len(status_list)}")
    
    # 测试统计信息获取
    start_time = time.time()
    stats = auto_committer.get_statistics()
    stats_time = time.time() - start_time
    print(f"   获取统计时间: {stats_time:.4f}秒")
    
    return len(status_list) > 0


def test_cli_responsiveness():
    """测试CLI响应性"""
    print("\n🔧 测试CLI响应性...")
    
    import subprocess
    
    commands = [
        ["python", "main.py", "--version"],
        ["python", "main.py", "config", "get", "--key", "global.log_level"],
        ["python", "main.py", "status"],
    ]
    
    for cmd in commands:
        print(f"📊 测试命令: {' '.join(cmd)}")
        start_time = time.time()
        try:
            result = subprocess.run(cmd, capture_output=True, text=True, timeout=10)
            end_time = time.time()
            
            if result.returncode == 0:
                print(f"   ✅ 执行时间: {end_time - start_time:.4f}秒")
            else:
                print(f"   ❌ 命令失败: {result.stderr}")
        except subprocess.TimeoutExpired:
            print(f"   ⏰ 命令超时 (>10秒)")
        except Exception as e:
            print(f"   ❌ 执行错误: {e}")


def main():
    """主测试函数"""
    print("🚀 Gitee自动提交工具 - 性能测试")
    print("=" * 50)
    
    # 配置管理性能测试
    config_ok = test_config_performance()
    
    # Git操作性能测试
    git_ok = test_git_performance()
    
    # 自动提交器性能测试
    committer_ok = test_auto_committer_performance()
    
    # CLI响应性测试
    test_cli_responsiveness()
    
    # 总结
    print("\n" + "=" * 50)
    print("📋 测试总结:")
    print(f"   配置管理: {'✅ 通过' if config_ok else '❌ 失败'}")
    print(f"   Git操作: {'✅ 通过' if git_ok else '❌ 失败'}")
    print(f"   自动提交器: {'✅ 通过' if committer_ok else '❌ 失败'}")
    
    if all([config_ok, git_ok, committer_ok]):
        print("\n🎉 所有性能测试通过！优化效果显著。")
    else:
        print("\n⚠️ 部分测试未通过，需要进一步优化。")


if __name__ == "__main__":
    main()
